package cn.tedu.bece.front.controller;

import cn.tedu.bece.front.common.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/upload")
public class UploadController {

    @Value("${app.upload.path}")
    private String uploadPath;

    @Value("${app.upload.url-prefix}")
    private String urlPrefix;

    private static final Map<String, String> CONTENT_TYPE_MAPPING = new HashMap<>();

    static {
        CONTENT_TYPE_MAPPING.put(".jpg", "image/jpg");
        CONTENT_TYPE_MAPPING.put(".jpeg", "image/jpg");
        CONTENT_TYPE_MAPPING.put(".png", "image/jpg");
        CONTENT_TYPE_MAPPING.put(".gif", "image/gif");
        CONTENT_TYPE_MAPPING.put(".bmp", "image/bmp");
    }

    @PostMapping("/image")
    public JsonResult uploadImage(MultipartFile file) {
        // 获取原文件名
        String originalFilename = file.getOriginalFilename();

        // 获取文件后缀
        int lastIndex;
        if (originalFilename == null || (lastIndex = originalFilename.lastIndexOf(".")) == -1) {
            return JsonResult.error("图片格式不支持");
        }
        String ext = originalFilename.substring(lastIndex).toLowerCase();

        // 获取内容类型
        String contentType = CONTENT_TYPE_MAPPING.get(ext);
        if (contentType == null) {
            return JsonResult.error("图片格式不支持");
        }

        // 生成新的文件名
        String fileName = UUID.randomUUID().toString().replace("-", "") + ext;

        // 生成存储文件夹
        String folder = "/images" + DateTimeFormatter.ofPattern("/yyyy/MM/dd/").format(LocalDateTime.now());
        File targetDir = new File(uploadPath, folder);
        if (!targetDir.exists()) targetDir.mkdirs();

        try {
            file.transferTo(new File(targetDir, fileName));
        } catch (IOException e) {
            log.error("上传图片异常: {}", e.getMessage());
            return JsonResult.error("上传图片失败，请稍后再试");
        }

        // 拼接完整的url地址，返回
        String url = urlPrefix + folder + fileName;
        return JsonResult.success(url);
    }

}
